package livechat;

import java.io.IOException;
import java.util.Date;
import java.util.Hashtable;
import java.util.Vector;

import javax.servlet.http.*;

import util.ServerToClient;

import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelPresence;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;
import com.google.gson.Gson;

@SuppressWarnings("serial")
public class ChannelDisconnectServlet extends HttpServlet{
	
	//private static final int NEW_MESSAGE = 1;
	//private static final int NEW_USER_JOIN = 2;
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
		req.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=UTF-8");
		
		ChannelService channelService = ChannelServiceFactory.getChannelService();
		ChannelPresence presence = channelService.parsePresence(req);

		MemcacheService syncCache = MemcacheServiceFactory.getMemcacheService();
		Vector<String> vUsers = (Vector<String>) syncCache.get("room1");
		if(vUsers != null)
		{
			String sUsername = presence.clientId().split("_")[1];
			if(vUsers.indexOf(sUsername) != -1)
			{
				vUsers.remove(sUsername);
				syncCache.put("room1", vUsers);
				
				receiveMessage(sUsername, "sign out");
				
				Hashtable hNewUser = new Hashtable();
				hNewUser.put("all_user", vUsers);
				ServerToClient.sendMessageToAllUsers(ServerToClient.NEW_USER_JOIN, hNewUser, "");
			}
		}		
    }
	
	private void receiveMessage(String sUsername, String sMessage)
	{
        if (sMessage != null) {
        	DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        	ChatLog chat = new ChatLog(sUsername, sMessage, new Date().getTime());
        	Entity chatlog = new Entity("chatlog");
        	chatlog.setProperty("username", chat.get_sUserName());
        	chatlog.setProperty("message", chat.get_sMessage());
        	chatlog.setProperty("time", chat.get_lTime());
        	datastore.put(chatlog);	    
        	
        	ServerToClient.sendMessageToAllUsers(ServerToClient.NEW_MESSAGE, chat, "");
        }		
	}

}
